<template>
  <el-dialog
    v-model="visible"
    :title="$t('contacts.requests.title')"
    width="700px"
    :before-close="handleClose"
  >
    <div class="requests-content">
      <!-- 标签页 -->
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane :label="$t('contacts.requests.received')" name="received">
          <div class="tab-header">
            <span class="tab-info">
              {{ $t('contacts.requests.requestsCount', { count: receivedRequests?.length || 0 }) }}
              <el-tag v-if="pendingReceivedCount > 0" type="warning" size="small">
                {{ $t('contacts.requests.pendingCount', { count: pendingReceivedCount }) }}
              </el-tag>
            </span>
            <el-button 
              size="small" 
              @click="loadReceivedRequests"
              :loading="loading"
            >
              {{ $t('common.refresh') }}
            </el-button>
          </div>
          
          <div class="requests-list" v-loading="loading">
            <div v-if="!receivedRequests || receivedRequests.length === 0" class="empty-state">
              <el-empty :description="$t('contacts.requests.noRequests')" />
            </div>

            <div v-else>
              <div
                v-for="request in receivedRequests"
                :key="request.id"
                class="request-item"
                :class="{ pending: request.status === 'PENDING' }"
              >
                <div class="request-avatar">
                  <el-avatar :src="request.fromUser.avatarUrl" :size="40">
                    {{ request.fromUser.realName?.charAt(0) || request.fromUser.username.charAt(0) }}
                  </el-avatar>
                </div>
                
                <div class="request-info">
                  <div class="request-header">
                    <span class="user-name">
                      {{ request.fromUser.realName || request.fromUser.username }}
                    </span>
                    <el-tag v-if="request.fromUser.userType === 'VIP'" type="warning" size="small">VIP</el-tag>
                    <el-tag v-if="request.fromUser.userType === 'ADMIN'" type="danger" size="small">{{ $t('contacts.friend.userTypes.admin') }}</el-tag>
                    <span class="request-time">
                      {{ formatTime(request.createdAt) }}
                    </span>
                  </div>
                  
                  <div class="request-message" v-if="request.message">
                    {{ request.message }}
                  </div>
                  
                  <div class="request-status">
                    <el-tag 
                      :type="getStatusType(request.status)" 
                      size="small"
                    >
                      {{ getStatusText(request.status) }}
                    </el-tag>
                    <span v-if="request.status === 'PENDING'" class="expire-info">
                      {{ getExpireText(request.expiresAt) }}
                    </span>
                  </div>
                  
                  <div v-if="request.responseMessage" class="response-message">
                    <strong>{{ $t('contacts.requests.responseMessage') }}</strong>{{ request.responseMessage }}
                  </div>
                </div>
                
                <div class="request-actions" v-if="request.status === 'PENDING'">
                  <el-button 
                    type="success" 
                    size="small"
                    @click="handleRequest(request, 'ACCEPT')"
                    :loading="processingRequests.has(request.id)"
                  >
                    {{ $t('contacts.requests.accept') }}
                  </el-button>
                  <el-button 
                    type="danger" 
                    size="small"
                    @click="handleRequest(request, 'REJECT')"
                    :loading="processingRequests.has(request.id)"
                  >
                    {{ $t('contacts.requests.reject') }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane :label="$t('contacts.requests.sent')" name="sent">
          <div class="tab-header">
            <span class="tab-info">
              {{ $t('contacts.requests.requestsCount', { count: sentRequests?.length || 0 }) }}
            </span>
            <el-button 
              size="small" 
              @click="loadSentRequests"
              :loading="loading"
            >
              刷新
            </el-button>
          </div>
          
          <div class="requests-list" v-loading="loading">
            <div v-if="!sentRequests || sentRequests.length === 0" class="empty-state">
              <el-empty :description="$t('contacts.requests.noRequests')" />
            </div>

            <div v-else>
              <div
                v-for="request in sentRequests"
                :key="request.id"
                class="request-item"
              >
                <div class="request-avatar">
                  <el-avatar :src="request.toUser.avatarUrl" :size="40">
                    {{ request.toUser.realName?.charAt(0) || request.toUser.username.charAt(0) }}
                  </el-avatar>
                </div>
                
                <div class="request-info">
                  <div class="request-header">
                    <span class="user-name">
                      {{ request.toUser.realName || request.toUser.username }}
                    </span>
                    <el-tag v-if="request.toUser.userType === 'VIP'" type="warning" size="small">VIP</el-tag>
                    <el-tag v-if="request.toUser.userType === 'ADMIN'" type="danger" size="small">{{ $t('contacts.friend.userTypes.admin') }}</el-tag>
                    <span class="request-time">
                      {{ formatTime(request.createdAt) }}
                    </span>
                  </div>
                  
                  <div class="request-message" v-if="request.message">
                    {{ request.message }}
                  </div>
                  
                  <div class="request-status">
                    <el-tag 
                      :type="getStatusType(request.status)" 
                      size="small"
                    >
                      {{ getStatusText(request.status) }}
                    </el-tag>
                    <span v-if="request.status === 'PENDING'" class="expire-info">
                      {{ getExpireText(request.expiresAt) }}
                    </span>
                  </div>
                  
                  <div v-if="request.responseMessage" class="response-message">
                    <strong>对方回复：</strong>{{ request.responseMessage }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 处理申请对话框 -->
    <el-dialog
      v-model="showHandleDialog"
      :title="handleAction === 'ACCEPT' ? '接受好友申请' : '拒绝好友申请'"
      width="400px"
      append-to-body
    >
      <el-form :model="handleForm" label-width="80px">
        <el-form-item label="申请人">
          <div class="handle-target">
            <el-avatar :src="selectedRequest?.fromUser.avatarUrl" :size="32">
              {{ selectedRequest?.fromUser.realName?.charAt(0) || selectedRequest?.fromUser.username.charAt(0) }}
            </el-avatar>
            <span class="target-name">
              {{ selectedRequest?.fromUser.realName || selectedRequest?.fromUser.username }}
            </span>
          </div>
        </el-form-item>
        
        <el-form-item v-if="selectedRequest?.message" label="申请消息">
          <div class="original-message">
            {{ selectedRequest.message }}
          </div>
        </el-form-item>
        
        <el-form-item label="回复消息">
          <el-input
            v-model="handleForm.responseMessage"
            type="textarea"
            :rows="3"
            :placeholder="handleAction === 'ACCEPT' ? '很高兴认识你！' : '抱歉，暂时不方便添加好友'"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showHandleDialog = false">取消</el-button>
        <el-button 
          :type="handleAction === 'ACCEPT' ? 'success' : 'danger'"
          @click="confirmHandleRequest"
          :loading="handlingRequest"
        >
          {{ handleAction === 'ACCEPT' ? '接受' : '拒绝' }}
        </el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useContactsStore } from '@/stores/contacts'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'

// Props & Emits
const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'handled': []
}>()

// 状态管理
const contactsStore = useContactsStore()

// 响应式数据
const activeTab = ref('received')
const loading = ref(false)
const receivedRequests = ref<any[]>([])
const sentRequests = ref<any[]>([])
const processingRequests = ref(new Set<number>())

const showHandleDialog = ref(false)
const selectedRequest = ref<any>(null)
const handleAction = ref<'ACCEPT' | 'REJECT'>('ACCEPT')
const handlingRequest = ref(false)

const handleForm = reactive({
  responseMessage: ''
})

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const pendingReceivedCount = computed(() => {
  return receivedRequests.value?.filter(req => req.status === 'PENDING').length || 0
})

// 生命周期
onMounted(() => {
  if (visible.value) {
    loadReceivedRequests()
  }
})

// 方法
const loadReceivedRequests = async () => {
  try {
    loading.value = true
    const response = await contactsStore.getReceivedRequests()
    receivedRequests.value = response?.content || []
  } catch (error) {
    console.error('加载收到的申请失败:', error)
    receivedRequests.value = []
  } finally {
    loading.value = false
  }
}

const loadSentRequests = async () => {
  try {
    loading.value = true
    const response = await contactsStore.getSentRequests()
    sentRequests.value = response?.content || []
  } catch (error) {
    console.error('加载发送的申请失败:', error)
    sentRequests.value = []
  } finally {
    loading.value = false
  }
}

const handleTabChange = (tabName: string) => {
  if (tabName === 'received' && receivedRequests.value.length === 0) {
    loadReceivedRequests()
  } else if (tabName === 'sent' && sentRequests.value.length === 0) {
    loadSentRequests()
  }
}

const handleRequest = (request: any, action: 'ACCEPT' | 'REJECT') => {
  selectedRequest.value = request
  handleAction.value = action
  handleForm.responseMessage = action === 'ACCEPT' ? '很高兴认识你！' : '抱歉，暂时不方便添加好友'
  showHandleDialog.value = true
}

const confirmHandleRequest = async () => {
  if (!selectedRequest.value) return

  try {
    handlingRequest.value = true
    processingRequests.value.add(selectedRequest.value.id)

    await contactsStore.handleFriendRequest(
      selectedRequest.value.id,
      handleAction.value,
      handleForm.responseMessage
    )

    // 更新本地数据
    const index = receivedRequests.value.findIndex(req => req.id === selectedRequest.value.id)
    if (index > -1) {
      receivedRequests.value[index].status = handleAction.value === 'ACCEPT' ? 'ACCEPTED' : 'REJECTED'
      receivedRequests.value[index].responseMessage = handleForm.responseMessage
    }

    showHandleDialog.value = false
    emit('handled')

  } catch (error) {
    console.error('处理好友申请失败:', error)
  } finally {
    handlingRequest.value = false
    processingRequests.value.delete(selectedRequest.value.id)
  }
}

const handleClose = () => {
  visible.value = false
}

const formatTime = (timeString: string) => {
  try {
    const date = new Date(timeString)
    return formatDistanceToNow(date, { addSuffix: true, locale: zhCN })
  } catch {
    return '未知时间'
  }
}

const getExpireText = (expiresAt: string) => {
  try {
    const expireDate = new Date(expiresAt)
    const now = new Date()
    if (expireDate <= now) {
      return '已过期'
    }
    return `${formatDistanceToNow(expireDate, { locale: zhCN })}后过期`
  } catch {
    return ''
  }
}

const getStatusType = (status: string) => {
  switch (status) {
    case 'PENDING': return 'warning'
    case 'ACCEPTED': return 'success'
    case 'REJECTED': return 'danger'
    case 'EXPIRED': return 'info'
    default: return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'PENDING': return '待处理'
    case 'ACCEPTED': return '已接受'
    case 'REJECTED': return '已拒绝'
    case 'EXPIRED': return '已过期'
    default: return '未知'
  }
}
</script>

<style scoped>
.requests-content {
  min-height: 400px;
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.tab-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.requests-list {
  max-height: 500px;
  overflow-y: auto;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.request-item {
  display: flex;
  gap: 12px;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid var(--el-border-color-lighter);
  margin-bottom: 12px;
  transition: all 0.2s;
}

.request-item.pending {
  border-color: var(--el-color-warning);
  background: var(--el-color-warning-light-9);
}

.request-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.request-info {
  flex: 1;
  min-width: 0;
}

.request-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.user-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.request-time {
  margin-left: auto;
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.request-message {
  margin-bottom: 8px;
  padding: 8px 12px;
  background: var(--el-fill-color-extra-light);
  border-radius: 6px;
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.request-status {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.expire-info {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.response-message {
  font-size: 12px;
  color: var(--el-text-color-regular);
  font-style: italic;
}

.request-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-self: flex-start;
}

.handle-target {
  display: flex;
  align-items: center;
  gap: 8px;
}

.target-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.original-message {
  padding: 8px 12px;
  background: var(--el-fill-color-extra-light);
  border-radius: 6px;
  font-size: 14px;
  color: var(--el-text-color-regular);
}
</style>
